package com.hand.pp.controller;/**
 * @author Estelle@앙수청
 * @date 2019/7/16 13:53
 */
import com.hand.pp.annotation.PermissionAnnotation;
import com.hand.pp.domain.Role;
import com.hand.pp.domain.User;
import com.hand.pp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 *  @author Estelle@앙수청
 *  @date 2019/7/16 13:53
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public ResponseEntity<List<User>> getAllUser(){
        return ResponseEntity.ok(userService.getAllUser());
    }

    @GetMapping(value = "/{id}")
    @PermissionAnnotation(value = true)
    public ResponseEntity<User> getUser(@PathVariable("id") Long id){
        return ResponseEntity.ok(userService.getUser(id));
    }

    @PostMapping
    @PermissionAnnotation(value = true)
    public ResponseEntity<Long> addUser(@RequestBody User user){
        return ResponseEntity.ok(userService.addUser(user));
    }

    @PutMapping
    @PermissionAnnotation(value = true)
    public ResponseEntity<Void> updateUser(@RequestBody User user){
        userService.updateUser(user);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping(value = "/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id){
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/all")
    @PermissionAnnotation(value = true)
    public ResponseEntity<List<User>> getUserByIds(@RequestParam("ids")List<Long> ids){
        // 避免NullPointerException异常 的Optional类
        return Optional.ofNullable(userService.queryUserByIds(ids))
                .map(item ->new ResponseEntity<>(item, HttpStatus.OK))
                .orElseThrow(() ->new RuntimeException("RUNTIME ERROR"));
    }

    @GetMapping(value = "/role/{id}")
    public ResponseEntity<List<Role>> queryUserRole(@PathVariable("id") Long id){
        return ResponseEntity.ok(userService.queryUserRole(id));
    }


}
